package com.rzwl.single.server.ctrl.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.rzwl.single.server.config.WxMaConfiguration;
import com.rzwl.single.server.dao.UserDao;
import com.rzwl.single.server.entity.WxUser;
import com.rzwl.single.server.error.ParamException;
import com.rzwl.single.server.tool.Constant;
import com.rzwl.single.server.utils.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserDao userJpa;
    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public String login(@PathVariable String appid, String code) {
        logger.info("login接口");
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            //this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            return JsonUtils.toJson(session);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @Transactional
    @PostMapping("/info")
    public JSONObject info(@PathVariable String appid, String sessionKey,
                           String signature, String rawData, String encryptedData, String iv,
                           HttpServletRequest request) throws ParamException {
        logger.info("info接口:{}",sessionKey);
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        if ( StringUtils.isBlank( sessionKey ) ){
            throw new ParamException("sessionKey 缺少");
        }
        // 用户信息校验
        boolean checkUserInfo = wxService.getUserService().checkUserInfo(sessionKey, rawData, signature);
        if (!checkUserInfo) {
           throw new ParamException("user check failed");
        }

        // 解密用户信息 todo 没有unionId, 找到方法
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxUser user1 = userJpa.findByOpenid(userInfo.getOpenId());
        if ( user1 == null ) {
            logger.info("用户第一次登陆，创建");
            user1 = new WxUser();
            user1.setOpenid( userInfo.getOpenId() );
            user1.setNickName( userInfo.getNickName() );
            user1.setGender( Integer.parseInt( userInfo.getGender() ) );
            user1.setLanguage( userInfo.getLanguage() );
            user1.setCity( userInfo.getCity() );
            user1.setProvince( userInfo.getProvince() );
            user1.setCountry( userInfo.getCountry() );
            user1.setAvatarUrl( userInfo.getAvatarUrl() );
            user1.setUnionid( userInfo.getUnionId() );

            user1 = userJpa.save( user1 );
        } else {

        }
        /*LogLogin login = new LogLogin();
        login.setUserId( user1.getId() );
        loginJpa.save( login );*/
        logger.info("登录用户:{}",user1.getId());
        HttpSession session = request.getSession();
        session.setAttribute(Constant.sessionName, user1 );

        logger.info("设置session属性");
        JSONObject res = (JSONObject) JSONObject.toJSON( user1 );
        res.put(Constant.seid, session.getId());
        return res;
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }

}
